#!/usr/bin/env python
# coding: utf-8
import sys
import random
import ping
import HostsLibaray

min=160
max=180

timeout=1000
packet_size=55
count=3
GoogleNormailHostPrefix = '203'
GoogleNormalHostAddr = '203.208.46.%s'
 
def getGdotCNIP():
    p = ping.Ping('www.g.cn', timeout, packet_size)
    p.run(count)
    return p.dest_ip
    

def getMostProbableIP():
    GdotCNIP = getGdotCNIP()
    if GdotCNIP.split('.')[0] != GoogleNormailHostPrefix:
        return GoogleNormalHostAddr%random.randint(min,max)
    else:
        return GdotCNIP
    

    
def fixGAEHost():
    Hosts = HostsLibaray.open('C:\WINDOWS\system32\drivers\etc\hosts')
    NewHosts = HostsLibaray.Hosts()
    HostIP = getMostProbableIP()
    
    for host, sites in Hosts.GetAllMappings().items():
        for site in sites:
            print host,site
            if(site.find('appspot.com')!=-1):
                NewHosts.Add({HostIP:site})
    
    HostsLibaray.save('C:\WINDOWS\system32\drivers\etc\hosts', NewHosts)

    
def justAddGAESite(newsite):
    Hosts = HostsLibaray.open('C:\WINDOWS\system32\drivers\etc\hosts')
    for host, sites in Hosts.GetAllMappings().items():
        for site in sites:
            if site.find('appspot.com')!=-1:
                Hosts.Add({host:newsite})
                HostsLibaray.save('C:\WINDOWS\system32\drivers\etc\hosts', Hosts)
                return
    
    
if __name__ == '__main__':
    if len(sys.argv)>1:
        justAddGAESite(sys.argv[1])
    fixGAEHost()
    
    